//
//  DetailViewController.m
//  ipadclient
//
//  Created by Stéphane Prohaszka on 28/04/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"

#import <AVFoundation/AVPlayer.h>
#import <AVFoundation/AVPlayerItem.h>
#import <AVFoundation/AVPlayerLayer.h>
#import <MediaPlayer/MPMoviePlayerController.h>

#import "RootViewController.h"

#import "ParleysService.h"
#import "Presentation.h"
#import "PresentationCell.h"

@interface DetailViewController ()
@property (nonatomic, retain) UIPopoverController *popoverController;
- (void)configureView;
@end

@implementation DetailViewController

@synthesize toolbar=_toolbar;
@synthesize detailItem=_detailItem;
@synthesize detailDescriptionLabel=_detailDescriptionLabel;
@synthesize popoverController=_myPopoverController;

@synthesize myTableView;

#pragma mark - Managing the detail item

/*
 When setting the detail item, update the view and dismiss the popover controller if it's showing.
 */
- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        [_detailItem release];
        _detailItem = [newDetailItem retain];
        
        // Update the view.
        [self configureView];
    }

    if (self.popoverController != nil) {
        [self.popoverController dismissPopoverAnimated:YES];
    }        
}

- (void)configureView
{
    // Update the user interface for the detail item.

    self.detailDescriptionLabel.text = [self.detailItem description];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (void)viewDidLoad {
    // Init attributes
    presentations = [[NSMutableArray alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateTable)
                                                 name:@"PresentationsLoaded"
                                               object:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return NO;
}

#pragma mark - Split view support

- (void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController: (UIPopoverController *)pc
{
    barButtonItem.title = @"Events";
    NSMutableArray *items = [[self.toolbar items] mutableCopy];
    [items insertObject:barButtonItem atIndex:0];
    [self.toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = pc;
}

// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    NSMutableArray *items = [[self.toolbar items] mutableCopy];
    [items removeObjectAtIndex:0];
    [self.toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = nil;
}

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
 */

- (void)viewDidUnload
{
	[super viewDidUnload];

	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.popoverController = nil;
}

#pragma mark - Memory management

- (void)didReceiveMemoryWarning
{
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

#pragma mark -
#pragma mark UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [presentations count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    PresentationCell *cell = (PresentationCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PresentationCell" owner:self options:nil];
		for (id oneObject in nib) {
			if ([oneObject isKindOfClass:[PresentationCell class]]) {
				cell = (PresentationCell *)oneObject;
			}
		}
    }
    
    Presentation* presentation = [presentations objectAtIndex:[indexPath row]];
    cell.title.text = presentation.title;
    //cell.title.text = [NSString stringWithFormat:@"%@ (%@: %@) ", presentation.title, NSLocalizedString(@"Play time", nil), @"arg"];
    NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:presentation.thumbnail]];
    UIImage* photo = [UIImage imageWithData:imageData];
    cell.photo.image = photo;
    cell.description.text = presentation.summary;
    cell.votes.text = [NSString stringWithFormat:@"%i", presentation.totalVotes];
    cell.downloads.text = [NSString stringWithFormat:@"%i", presentation.totalDownloads];

    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Presentation* prez = [presentations objectAtIndex:[indexPath row]];
    NSLog(@"Presentation selected: %@ with URL %@", prez.title, prez.asset);
    //NSURL* videoUrl = [NSURL URLWithString:prez.asset];
    //NSURL* videoUrl = [NSURL URLWithString:@"http://s1.parleys.com/parleys/_definst_/2103/mp4:201011240955287223769.mp4/playList.m3u8"];
    //NSURL* videoUrl = [NSURL URLWithString:@"http://s1.parleys.com/parleys/_definst_/2168/mp4:201012010832150015541.mp4/playList.m3u8"];
    NSURL* videoUrl = [NSURL URLWithString:@"http://s1.parleys.com/parleys/_definst_/2168/mp4:201012010832526765571.mp4/playList.m3u8"];
    
    /*
    //AVPlayer* player = [[AVPlayer alloc] initWithURL:videoUrl];
    AVPlayerItem* item = [[AVPlayerItem alloc] initWithURL:videoUrl];
    AVPlayer* player = [[AVPlayer alloc] initWithPlayerItem:item];
    
    UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    newView.backgroundColor = [UIColor blackColor];
    
    AVPlayerLayer *avPlayerLayer = [[AVPlayerLayer playerLayerWithPlayer:player] retain];
    avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [newView.layer addSublayer:avPlayerLayer];
    [self.view addSubview:newView];
    [player play];
     */
    
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoUrl];
    [player.view setFrame:self.view.bounds];  // player's frame must match parent's
    [self.view addSubview: player.view];
    [player play];
    player.fullscreen = YES;
}

#pragma mark -
#pragma mark Custom
- (void)updateTable {
    NSLog(@"Update DetailView");
    ParleysService* service = [ParleysService sharedService];
    presentations = service.presentations;
    [myTableView reloadData];
}

- (void)dealloc
{
    [_myPopoverController release];
    [_toolbar release];
    [_detailItem release];
    [_detailDescriptionLabel release];
    [super dealloc];
}

@end
